package com.my.controller;

import com.alibaba.fastjson.JSON;
import com.my.pojo.Student;
import com.my.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class StudentController {

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private StudentService studentService;

    @RequestMapping("/all")
    public String findAll(Model model){
        List<Student> list=studentService.findAll();
        model.addAttribute("students",list);
        return "studentList";
    }


    @RequestMapping("/like")
    @ResponseBody
    public String likeStudent(HttpServletRequest request){
        return studentService.likeStudent("张").toString();
    }

    @RequestMapping("/add")
    public String add(){
        return "addStudent";
    }

    @RequestMapping("/insertTo")
    public String insertTo(HttpServletRequest request) throws ParseException {
        Student student=new Student();
        student.setSname(request.getParameter("name"));
        student.setSex(request.getParameter("sex"));
        student.setBirthday(sf.parse(request.getParameter("birthday")));
        student.setHobbies(request.getParameter("hobbies"));
        studentService.insertTo(student);
        return "redirect:/all";
    }

    @RequestMapping("/update")
    public String update(HttpServletRequest request) throws ParseException {
        Student student=new Student();
        Integer id=Integer.parseInt(request.getParameter("id"));
        student.setId(id);
        student.setSname(request.getParameter("name"));
        student.setSex(request.getParameter("sex"));
        student.setBirthday(sf.parse(request.getParameter("birthday")));
        student.setHobbies(request.getParameter("hobbies"));
        System.out.println(student);
        studentService.updateTo(student);
        return "redirect:/all";
    }

    @RequestMapping("/upd/{id}")
    public String update(@PathVariable("id")int id, Model model){
        System.out.println(id);
        Student student=studentService.findById(id);
        model.addAttribute("student",student);
        return "updateStudent";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id")int id){
        studentService.deleteTo(id);
        return "redirect:/all";
    }

    @RequestMapping("/queryStu")
    @ResponseBody
    public String query(String sname){
        List<Student> students=studentService.likeStudent(sname);
        String list= JSON.toJSONString(students);
        return list;
    }
}